{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9441da00",
   "metadata": {},
   "source": [
    "## Building Technical Strategies with VectorBT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d31b2588",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install vectorbt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c3822570",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import vectorbt as vbt\n",
    "from IPython.display import Markdown, display"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "600e5dcc",
   "metadata": {},
   "source": [
    "Define the start and end dates for data download"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f55cea83",
   "metadata": {},
   "outputs": [],
   "source": [
    "start = \"2016-01-01 UTC\"\n",
    "end = \"2020-01-01 UTC\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e797359",
   "metadata": {},
   "source": [
    "Download historical closing prices for specified symbols from Yahoo Finance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "39619e14",
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = vbt.YFData.download(\n",
    "    [\"META\", \"AAPL\", \"AMZN\", \"NFLX\", \"GOOG\"], start=start, end=end\n",
    ").get(\"Close\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74004828",
   "metadata": {},
   "source": [
    "Calculate fast and slow moving averages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c6c39111",
   "metadata": {},
   "outputs": [],
   "source": [
    "fast_ma = vbt.MA.run(prices, 10, short_name=\"fast\")\n",
    "slow_ma = vbt.MA.run(prices, 30, short_name=\"slow\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b58c05f4",
   "metadata": {},
   "source": [
    "Generate entry signals when the fast MA crosses above the slow MA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d4c17a2f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th>fast_window</th>\n",
       "      <th colspan=\"5\" halign=\"left\">10</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>slow_window</th>\n",
       "      <th colspan=\"5\" halign=\"left\">30</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>symbol</th>\n",
       "      <th>META</th>\n",
       "      <th>AAPL</th>\n",
       "      <th>AMZN</th>\n",
       "      <th>NFLX</th>\n",
       "      <th>GOOG</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2016-01-04 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-05 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-06 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-07 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-08 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-24 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-26 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-27 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-30 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-31 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1006 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "fast_window                   10                            \n",
       "slow_window                   30                            \n",
       "symbol                      META   AAPL   AMZN   NFLX   GOOG\n",
       "Date                                                        \n",
       "2016-01-04 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-05 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-06 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-07 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-08 05:00:00+00:00  False  False  False  False  False\n",
       "...                          ...    ...    ...    ...    ...\n",
       "2019-12-24 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-26 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-27 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-30 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-31 05:00:00+00:00  False  False  False  False  False\n",
       "\n",
       "[1006 rows x 5 columns]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "entries = fast_ma.ma_crossed_above(slow_ma)\n",
    "display(entries)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b0d9b1d",
   "metadata": {},
   "source": [
    "Generate exit signals when the fast MA crosses below the slow MA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "225bc5d3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th>fast_window</th>\n",
       "      <th colspan=\"5\" halign=\"left\">10</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>slow_window</th>\n",
       "      <th colspan=\"5\" halign=\"left\">30</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>symbol</th>\n",
       "      <th>META</th>\n",
       "      <th>AAPL</th>\n",
       "      <th>AMZN</th>\n",
       "      <th>NFLX</th>\n",
       "      <th>GOOG</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2016-01-04 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-05 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-06 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-07 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2016-01-08 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-24 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-26 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-27 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-30 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2019-12-31 05:00:00+00:00</th>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1006 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "fast_window                   10                            \n",
       "slow_window                   30                            \n",
       "symbol                      META   AAPL   AMZN   NFLX   GOOG\n",
       "Date                                                        \n",
       "2016-01-04 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-05 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-06 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-07 05:00:00+00:00  False  False  False  False  False\n",
       "2016-01-08 05:00:00+00:00  False  False  False  False  False\n",
       "...                          ...    ...    ...    ...    ...\n",
       "2019-12-24 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-26 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-27 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-30 05:00:00+00:00  False  False  False  False  False\n",
       "2019-12-31 05:00:00+00:00  False  False  False  False  False\n",
       "\n",
       "[1006 rows x 5 columns]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "exits = fast_ma.ma_crossed_below(slow_ma)\n",
    "display(exits)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a644c22",
   "metadata": {},
   "source": [
    "Create a portfolio using the generated entry and exit signals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b468d203",
   "metadata": {},
   "outputs": [],
   "source": [
    "pf = vbt.Portfolio.from_signals(prices, entries, exits, freq=\"1d\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af05b7a2",
   "metadata": {},
   "source": [
    "Display portfolio statistics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "47c13a9a",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/5j/6vs4zprx4fqcwl49nsw0hzqc0000gn/T/ipykernel_527/4100483198.py:1: UserWarning: Object has multiple columns. Aggregating using <function mean at 0x103be6cb0>. Pass column to select a single column/group.\n",
      "  display(pf.stats())\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Start                          2016-01-04 05:00:00+00:00\n",
       "End                            2019-12-31 05:00:00+00:00\n",
       "Period                                1006 days 00:00:00\n",
       "Start Value                                        100.0\n",
       "End Value                                     176.376667\n",
       "Total Return [%]                               76.376667\n",
       "Benchmark Return [%]                          152.731377\n",
       "Max Gross Exposure [%]                             100.0\n",
       "Total Fees Paid                                      0.0\n",
       "Max Drawdown [%]                               25.869064\n",
       "Max Drawdown Duration                  347 days 00:00:00\n",
       "Total Trades                                        17.4\n",
       "Total Closed Trades                                 16.4\n",
       "Total Open Trades                                    1.0\n",
       "Open Trade PnL                                  23.09785\n",
       "Win Rate [%]                                    49.79085\n",
       "Best Trade [%]                                  27.62887\n",
       "Worst Trade [%]                                -9.917979\n",
       "Avg Winning Trade [%]                          11.338861\n",
       "Avg Losing Trade [%]                           -4.898298\n",
       "Avg Winning Trade Duration    57 days 06:51:00.779220779\n",
       "Avg Losing Trade Duration               18 days 04:02:24\n",
       "Profit Factor                                   2.246469\n",
       "Expectancy                                      3.371259\n",
       "Sharpe Ratio                                    0.955982\n",
       "Calmar Ratio                                    1.017459\n",
       "Omega Ratio                                     1.205932\n",
       "Sortino Ratio                                   1.460596\n",
       "Name: agg_func_mean, dtype: object"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(pf.stats())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97415690",
   "metadata": {},
   "source": [
    "Plot the total return of the portfolio for each symbol"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "70762ceb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f8b348b2a22e4deaa9fe793879531ffa",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "FigureWidget({\n",
       "    'data': [{'name': 'total_return',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': 'ecfe6e6e-1885-483b-b912-8c223cc7f0b9',\n",
       "              'x': array(['AAPL', 'AMZN', 'GOOG', 'META', 'NFLX'], dtype=object),\n",
       "              'y': array([1.73482949, 1.28553102, 0.50135311, 0.16619102, 0.13092872])}],\n",
       "    'layout': {'height': 350,\n",
       "               'legend': {'orientation': 'h',\n",
       "                          'traceorder': 'normal',\n",
       "                          'x': 1,\n",
       "                          'xanchor': 'right',\n",
       "                          'y': 1.02,\n",
       "                          'yanchor': 'bottom'},\n",
       "               'margin': {'b': 30, 'l': 30, 'r': 30, 't': 30},\n",
       "               'template': '...',\n",
       "               'width': 700}\n",
       "})"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(pf.total_return().groupby(\"symbol\").mean().vbt.barplot())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1a1753d",
   "metadata": {},
   "source": [
    "Create a portfolio assuming buy-and-hold strategy and plot the total return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8082d1e8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "46013ceeabb54e1db997996ec3b63a2e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "FigureWidget({\n",
       "    'data': [{'name': 'total_return',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': '2be586f5-48db-49c9-b740-0b9f0e7668e5',\n",
       "              'x': array(['AAPL', 'AMZN', 'GOOG', 'META', 'NFLX'], dtype=object),\n",
       "              'y': array([1.9828338 , 1.90089315, 0.80230228, 1.00792404, 1.94261559])}],\n",
       "    'layout': {'height': 350,\n",
       "               'legend': {'orientation': 'h',\n",
       "                          'traceorder': 'normal',\n",
       "                          'x': 1,\n",
       "                          'xanchor': 'right',\n",
       "                          'y': 1.02,\n",
       "                          'yanchor': 'bottom'},\n",
       "               'margin': {'b': 30, 'l': 30, 'r': 30, 't': 30},\n",
       "               'template': '...',\n",
       "               'width': 700}\n",
       "})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(\n",
    "    vbt.Portfolio.from_holding(prices, freq=\"1d\")\n",
    "    .total_return()\n",
    "    .groupby(\"symbol\")\n",
    "    .mean()\n",
    "    .vbt.barplot()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61e0f8cd",
   "metadata": {},
   "source": [
    "Split the prices data into 4 equal parts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9bb4ea8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "mult_prices, _ = prices.vbt.range_split(n=4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb7ad95b",
   "metadata": {},
   "source": [
    "Calculate fast and slow moving averages for each split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "19c045eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "fast_ma = vbt.MA.run(mult_prices, [10, 20], short_name=\"fast\")\n",
    "slow_ma = vbt.MA.run(mult_prices, [30, 30], short_name=\"slow\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ec72e57",
   "metadata": {},
   "source": [
    "Generate entry and exit signals for each split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "cc56470a",
   "metadata": {},
   "outputs": [],
   "source": [
    "entries = fast_ma.ma_crossed_above(slow_ma)\n",
    "exits = fast_ma.ma_crossed_below(slow_ma)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3a2839f",
   "metadata": {},
   "source": [
    "Create a portfolio using the generated entry and exit signals for each split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b446be7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "pf = vbt.Portfolio.from_signals(mult_prices, entries, exits, freq=\"1D\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae997c15",
   "metadata": {},
   "source": [
    "Plot the total return of the portfolio for each split and symbol"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "cf9b80cd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "49606e7ba0ea47e485f7a44061bd7689",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "FigureWidget({\n",
       "    'data': [{'name': 'AAPL',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': 'f93655bc-8da5-4171-aa99-dded0c613b44',\n",
       "              'x': array([0, 1, 2, 3]),\n",
       "              'y': array([0.05063187, 0.11321493, 0.10540564, 0.44102581])},\n",
       "             {'name': 'AMZN',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': 'afe7a2b2-737a-4e1f-b010-cb9d3a0836da',\n",
       "              'x': array([0, 1, 2, 3]),\n",
       "              'y': array([0.30121359, 0.10976334, 0.26265571, 0.01039871])},\n",
       "             {'name': 'GOOG',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': 'de6f7a15-8ad4-4765-9fec-b75aeb4bfaec',\n",
       "              'x': array([0, 1, 2, 3]),\n",
       "              'y': array([-0.08226513,  0.17835164,  0.0114838 ,  0.13153595])},\n",
       "             {'name': 'META',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': '10d34a04-ba1a-428f-a795-208078c38ffe',\n",
       "              'x': array([0, 1, 2, 3]),\n",
       "              'y': array([-0.04147423,  0.08015965, -0.13614617,  0.1027734 ])},\n",
       "             {'name': 'NFLX',\n",
       "              'showlegend': True,\n",
       "              'type': 'bar',\n",
       "              'uid': 'f2ccae3c-dc07-46c1-acae-f3ccc08b209f',\n",
       "              'x': array([0, 1, 2, 3]),\n",
       "              'y': array([-0.05867257, -0.03627905,  0.0439421 , -0.07218557])}],\n",
       "    'layout': {'height': 350,\n",
       "               'legend': {'orientation': 'h',\n",
       "                          'traceorder': 'normal',\n",
       "                          'x': 1,\n",
       "                          'xanchor': 'right',\n",
       "                          'y': 1.02,\n",
       "                          'yanchor': 'bottom'},\n",
       "               'margin': {'b': 30, 'l': 30, 'r': 30, 't': 30},\n",
       "               'template': '...',\n",
       "               'width': 700}\n",
       "})"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(\n",
    "    pf.total_return()\n",
    "    .groupby([\"split_idx\", \"symbol\"])\n",
    "    .mean()\n",
    "    .unstack(level=-1)\n",
    "    .vbt.barplot()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6a9f92d",
   "metadata": {},
   "source": [
    "Display order statistics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "00a75a60",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Start                                0\n",
       "End                                250\n",
       "Period               251 days 00:00:00\n",
       "Total Records                      291\n",
       "Total Buy Orders                   157\n",
       "Total Sell Orders                  134\n",
       "Min Size                      0.253075\n",
       "Max Size                      4.689545\n",
       "Avg Size                      1.631434\n",
       "Avg Buy Size                  1.640189\n",
       "Avg Sell Size                 1.621176\n",
       "Avg Buy Price               103.424691\n",
       "Avg Sell Price              104.548087\n",
       "Total Fees                         0.0\n",
       "Min Fees                           0.0\n",
       "Max Fees                           0.0\n",
       "Avg Fees                           0.0\n",
       "Avg Buy Fees                       0.0\n",
       "Avg Sell Fees                      0.0\n",
       "Name: group, dtype: object"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(pf.orders.stats(group_by=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27f755db",
   "metadata": {},
   "source": [
    "Display the Sharpe ratio of the portfolio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "42dbaaf6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "fast_window  slow_window  split_idx  symbol\n",
       "10           30           0          META     -0.472596\n",
       "                                     AAPL      1.125229\n",
       "                                     AMZN      1.633329\n",
       "                                     NFLX     -0.470585\n",
       "                                     GOOG     -0.051110\n",
       "                          1          META      0.449943\n",
       "                                     AAPL      1.043127\n",
       "                                     AMZN      0.611364\n",
       "                                     NFLX     -0.359590\n",
       "                                     GOOG      1.754604\n",
       "                          2          META     -0.572692\n",
       "                                     AAPL      0.049774\n",
       "                                     AMZN      1.255488\n",
       "                                     NFLX     -0.171628\n",
       "                                     GOOG      0.088257\n",
       "                          3          META      0.556394\n",
       "                                     AAPL      2.921353\n",
       "                                     AMZN      0.373490\n",
       "                                     NFLX     -0.591651\n",
       "                                     GOOG      1.090826\n",
       "20           30           0          META     -0.269871\n",
       "                                     AAPL     -0.075991\n",
       "                                     AMZN      2.011461\n",
       "                                     NFLX      0.367359\n",
       "                                     GOOG     -1.511734\n",
       "                          1          META      1.169299\n",
       "                                     AAPL      1.154899\n",
       "                                     AMZN      1.101583\n",
       "                                     NFLX      0.071964\n",
       "                                     GOOG      1.514199\n",
       "                          2          META     -0.509355\n",
       "                                     AAPL      1.567437\n",
       "                                     AMZN      2.423336\n",
       "                                     NFLX      0.837490\n",
       "                                     GOOG      0.267124\n",
       "                          3          META      1.106601\n",
       "                                     AAPL      2.823869\n",
       "                                     AMZN     -0.030273\n",
       "                                     NFLX     -0.088711\n",
       "                                     GOOG      1.010647\n",
       "Name: sharpe_ratio, dtype: float64"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(pf.sharpe_ratio())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34140cce",
   "metadata": {},
   "source": [
    "**Jason Strimpel** is the founder of <a href='https://pyquantnews.com/'>PyQuant News</a> and co-founder of <a href='https://www.tradeblotter.io/'>Trade Blotter</a>. His career in algorithmic trading spans 20+ years. He previously traded for a Chicago-based hedge fund, was a risk manager at JPMorgan, and managed production risk technology for an energy derivatives trading firm in London. In Singapore, he served as APAC CIO for an agricultural trading firm and built the data science team for a global metals trading firm. Jason holds degrees in Finance and Economics and a Master's in Quantitative Finance from the Illinois Institute of Technology. His career spans America, Europe, and Asia. He shares his expertise through the <a href='https://pyquantnews.com/subscribe-to-the-pyquant-newsletter/'>PyQuant Newsletter</a>, social media, and has taught over 1,000+ algorithmic trading with Python in his popular course **<a href='https://gettingstartedwithpythonforquantfinance.com/'>Getting Started With Python for Quant Finance</a>**. All code is for educational purposes only. Nothing provided here is financial advise. Use at your own risk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42786026-97a0-4fc4-aa97-6e68f41393af",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
